<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>公司信息配置</span>
        </div>
      </template>

      <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px" class="company-form">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="公司名称" prop="companyName">
              <el-input v-model="formData.companyName" placeholder="请输入公司名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公司地址" prop="companyAddress">
              <el-input v-model="formData.companyAddress" placeholder="请输入公司地址" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="邮政编码" prop="postalCode">
              <el-input v-model="formData.postalCode" placeholder="请输入邮政编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人" prop="contactPerson">
              <el-input v-model="formData.contactPerson" placeholder="请输入联系人" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号" prop="mobilePhone">
              <el-input v-model="formData.mobilePhone" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电话号" prop="telephone">
              <el-input v-model="formData.telephone" placeholder="请输入电话号" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="传真" prop="fax">
              <el-input v-model="formData.fax" placeholder="请输入传真" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电子邮箱" prop="email">
              <el-input v-model="formData.email" placeholder="请输入电子邮箱" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="QQ号码" prop="qqNumber">
              <el-input v-model="formData.qqNumber" placeholder="请输入QQ号码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="微信二维码" prop="wechatQrCodeUrl">
              <ImageSelector type="img" v-model:imgUrl="formData.wechatQrCodeUrl" :preview-src-list="[formData.wechatQrCodeUrl]" />
              <!-- <div class="qr-upload-container">
                <div v-if="formData.wechatQrCodeUrl" class="qr-preview">
                  <img :src="formData.wechatQrCodeUrl" alt="微信二维码" class="qr-image" />
                  <div class="qr-actions">
                    <el-button size="small" @click="handleUploadWechatQr">重新上传</el-button>
                    <el-button size="small" type="danger" @click="handleRemoveWechatQr">删除</el-button>
                  </div>
                </div>
                <div v-else class="qr-upload-placeholder">
                  <el-button type="primary" @click="handleUploadWechatQr">上传微信二维码</el-button>
                  <div class="upload-tip">支持 PNG、JPG、JPEG 格式</div>
                </div>
              </div> -->
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="公众号二维码" prop="officialAccountQrCodeUrl">
              <ImageSelector type="img" v-model:imgUrl="formData.officialAccountQrCodeUrl" :preview-src-list="[formData.officialAccountQrCodeUrl]" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="营业执照" prop="businessLicense">
              <ImageSelector type="img" v-model:imgUrl="formData.businessLicense" :preview-src-list="[formData.businessLicense]" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="营业执照副本" prop="businessLicenseCopy">
              <ImageSelector type="img" v-model:imgUrl="formData.businessLicenseCopy" :preview-src-list="[formData.businessLicenseCopy]" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="公司介绍" prop="companyDescription">
          <el-input v-model="formData.companyDescription" type="textarea" :rows="3" placeholder="请输入公司介绍简述" />
        </el-form-item>

        <el-form-item label="其他信息" prop="otherInfo">
          <el-input v-model="formData.otherInfo" type="textarea" :rows="3" placeholder="请输入其他信息" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="loading">
            {{ isEdit ? "更新" : "保存" }}
          </el-button>
          <el-button @click="handleGoBack">返回</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from "element-plus";
import { getCompanyInfo, createCompanyInfo, updateCompanyInfo } from "@/api/common";
import { useRouter } from "vue-router";
import ImageSelector from "@/components/ImageSelector/index.vue";

// 表单引用
const formRef = ref<FormInstance>();

// 加载状态
const loading = ref(false);

// 是否为编辑模式
const isEdit = ref(false);

const router = useRouter();

// 表单数据
const formData = reactive({
  _id: "",
  companyName: "",
  companyAddress: "",
  companyDescription: "",
  postalCode: "",
  contactPerson: "",
  mobilePhone: "",
  telephone: "",
  fax: "",
  email: "",
  qqNumber: "",
  wechatQrCodeUrl: "",
  officialAccountQrCodeUrl: "",
  businessLicense: "",
  businessLicenseCopy: "",
  otherInfo: ""
});

// 表单验证规则
const rules: FormRules = {
  companyName: [{ required: true, message: "公司名称不能为空", trigger: "blur" }],
  email: [
    {
      pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
      message: "请输入正确的邮箱格式",
      trigger: "blur"
    }
  ],
  mobilePhone: [
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号格式",
      trigger: "blur"
    }
  ]
};

/**
 * 获取公司信息数据
 * 从接口获取已配置的公司信息
 */
const fetchCompanyInfo = async () => {
  try {
    const res = await getCompanyInfo();
    console.log(res, "res");

    if (res.data && res.data._id) {
      // 有数据，编辑模式
      isEdit.value = true;
      Object.assign(formData, res.data);
    } else {
      // 无数据，新增模式
      isEdit.value = false;
    }
  } catch (error) {
    console.error("获取公司信息失败:", error);
    ElMessage.error("获取公司信息失败");
  }
};

/**
 * 提交表单数据
 * 根据是否有_id判断调用新增或更新接口
 */
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    loading.value = true;

    if (isEdit.value && formData._id) {
      // 更新公司信息 - 去除_id字段
      const { _id, ...updateData } = formData;
      await updateCompanyInfo(_id, updateData);
      ElMessage.success("公司信息更新成功");
    } else {
      // 创建公司信息，不传递_id字段
      const { _id, ...createData } = formData;
      const res = await createCompanyInfo(createData);
      if (res.data && res.data._id) {
        formData._id = res.data._id;
        isEdit.value = true;
      }
      ElMessage.success("公司信息保存成功");
    }
  } catch (error) {
    console.error("保存公司信息失败:", error);
    ElMessage.error("保存公司信息失败");
  } finally {
    loading.value = false;
  }
};

/**
 * 返回上一页
 */
const handleGoBack = () => {
  router.go(-1);
};

// 页面挂载时获取数据
onMounted(() => {
  fetchCompanyInfo();
});
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.box-card {
  max-width: 1200px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
}

.company-form {
  padding: 20px 0;
}

.el-form-item {
  margin-bottom: 24px;
}

.el-textarea {
  width: 100%;
}
</style>
